//
//  FindSitesViewController.m
//  AirConditioner
//
//  Created by Sean Wang on 12-4-24.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "FindSitesViewController.h"
#import "BrandBottomViewController.h"
#import "SitesResultsViewController.h"

@interface FindSitesViewController ()

@end

@implementation FindSitesViewController

@synthesize postcodeField, suburbField, searchNearBy, indicator;
@synthesize currentState, locationManager;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init];
        temporaryBarButtonItem.title = @"Back";
        self.navigationItem.backBarButtonItem = temporaryBarButtonItem;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIViewController *viewController = [[BrandBottomViewController alloc] initWithNibName:@"BrandBottomView" bundle:nil];
    //viewController.view.backgroundColor = [UIColor purpleColor];
    [self.view addSubview:viewController.view];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.currentState == findRetailer) {
        self.title = @"Find a Retailer";
    }else if(self.currentState == findSpecialist){
        self.title = @"Find a Specialist";
    }
    //self.indicator.hidden = YES;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if ([self.postcodeField isFirstResponder]) {
        [self.postcodeField resignFirstResponder];
    }else if ([self.suburbField isFirstResponder]) {
        [self.suburbField resignFirstResponder];
    }
    
}

- (IBAction)go:(id)sender
{
    UIButton *button = (UIButton*)sender;
    switch (button.tag) {
        case 1:
            [self findSitesByPostcode];
            break;
        case 2:
            [self findSitesBySuburb];
            break;
        
        default:
            break;
    }

}

- (void) findSitesByPostcode
{
    NSString *postcode = self.postcodeField.text;
    if (postcode.length == 0) {
        [self alert:@"Postcode is Blank" message:@"Please enter a postcode"];
        return;
    }
    
    [self gotoResultsView]; 
}

- (void) findSitesBySuburb
{
    NSString *suburb = self.suburbField.text;
    if (suburb.length == 0) {
        [self alert:@"Suburb is Blank" message:@"Please enter a suburb"];
        return;
    }
    [self gotoResultsView];
}

- (void)alert:(NSString *)title message:(NSString *)message
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:message
                                                       delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    
	[alertView show];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    NSString *suburb = self.suburbField.text;
    if (suburb.length == 0) {
        [self alert:@"Suburb is Blank" message:@"Please enter a suburb"];
        return NO;
    }
    
    [textField resignFirstResponder];
    [self gotoResultsView];
    return YES;
    
}

- (void) gotoResultsView
{
    if(sitesResultsViewController == nil){
        sitesResultsViewController = [[SitesResultsViewController alloc]
                                      initWithNibName:@"SitesResultsViewController" bundle:nil];
    }
    
    [[self navigationController] pushViewController:sitesResultsViewController animated:YES];
}

- (void) gotoResultsView:(CLLocationCoordinate2D)coordinate
{
    if(sitesResultsViewController == nil){
        sitesResultsViewController = [[SitesResultsViewController alloc]
                                      initWithNibName:@"SitesResultsViewController" bundle:nil];
    }
    
    sitesResultsViewController.coordinate = coordinate;
    
    [[self navigationController] pushViewController:sitesResultsViewController animated:YES];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark Location Manager Interactions

- (IBAction)searchNearBy:(id)sender
{    
    self.searchNearBy.text = @"UPDATING LOCATION";
    if (self.indicator.isAnimating == NO) [self.indicator startAnimating];
    if(locationManager == nil){
        locationManager = [[CLLocationManager alloc] init];        
    }
    
    locationManager.delegate = self;
    // This is the most important property to set for the manager. It ultimately determines how the manager will
    // attempt to acquire location and thus, the amount of power that will be consumed.
    locationManager.desiredAccuracy = 100.0;
    // Once configured, the location manager must be "started".
    [locationManager startUpdatingLocation];
    
    [self performSelector:@selector(stopUpdatingLocation:) withObject:@"Timed Out" afterDelay:45];
    //[self gotoResultsView]; 
    //[self performSelector:@selector(gotoResultsView) withObject:nil afterDelay:2];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    
    // test the age of the location measurement to determine if the measurement is cached
    // in most cases you will not want to rely on cached measurements
    NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
    //NSLog(@"locationAge: %f",locationAge);
    
    if (locationAge > 5.0) return;
    // test that the horizontal accuracy does not indicate an invalid measurement
    if (newLocation.horizontalAccuracy < 0) return;

    if (newLocation.horizontalAccuracy <= locationManager.desiredAccuracy) {
        //NSLog(@"newLocation.horizontalAccuracy: %f",newLocation.horizontalAccuracy);
        //NSLog(@"locationManager.desiredAccuracy: %f",locationManager.desiredAccuracy);
        
        // we have a measurement that meets our requirements, so we can stop updating the location
        // 
        // IMPORTANT!!! Minimize power usage by stopping the location manager as soon as possible.
        //
        [self stopUpdatingLocation:@"SEARCH NEARBY"];
        
        // we need cancel our previous performSelector:withObject:afterDelay: - it's no longer necessary
        NSLog(@"cancelPreviousPerformRequestsWithTarget");
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(stopUpdatingLocation:) object:@"Timed Out"];
        
        currentLocation = newLocation;  
        CLLocationCoordinate2D coordinate = [currentLocation coordinate];
        [self gotoResultsView:coordinate];
    }   
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"didFailWithError: %d", [error code]);
    // The location "unknown" error simply means the manager is currently unable to get the location.
    // We can ignore this error for the scenario of getting a single location fix, because we already have a timeout that will stop the location manager to save power.
    if ([error code] != kCLErrorLocationUnknown) {
        UIAlertView *servicesDisabledAlert = [[UIAlertView alloc] initWithTitle:nil message:@"Turn On Location Services to Allow \"NCG Airconditioning\" to Determine Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [servicesDisabledAlert show];
        [self stopUpdatingLocation:@"Error"];
        
        // we need cancel our previous performSelector:withObject:afterDelay: - it's no longer necessary
        NSLog(@"cancelPreviousPerformRequestsWithTarget");
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(stopUpdatingLocation:) object:@"Timed Out"];
    }
}

- (void)stopUpdatingLocation:(NSString *)state {
    NSLog(@"stopUpdatingLocation: %@", state);
    if([state isEqualToString:@"Timed Out"]){
        UIAlertView *servicesDisabledAlert = [[UIAlertView alloc] initWithTitle:nil message:@"The location service is currently unable to get the location. Please try it later." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [servicesDisabledAlert show];

    }
    [locationManager stopUpdatingLocation];
    locationManager.delegate = nil;
    self.searchNearBy.text = @"SEARCH NEARBY";
    [self.indicator stopAnimating];
    
}


@end
